package stundenplan;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import android.util.Log;
import android.widget.LinearLayout;
import android.widget.ListView;
import de.app.badresden.AnimationTouchListener;
import de.app.badresden.R;

public class StundenplanScreenBuilder {

	private boolean updateFlipperOne;
	private List<Unterrichtstag> unterrichtstage;
	private StundenplanActivity activity;
	private AnimationTouchListener touchListener;

	public StundenplanScreenBuilder(StundenplanActivity activity,
			AnimationTouchListener touchListener) {

		this.touchListener = touchListener;
		this.activity = activity;
	}

	public void ImportUnterrichtstage(ArrayList<Unterrichtstag> unterrichtstage) {

		this.unterrichtstage = unterrichtstage;
	}

	public void updateStundenplan(Calendar cal, LinearLayout flipper) {

		getActiveFlipper(flipper);
		ListView listView;

		if (updateFlipperOne) listView = (ListView) flipper
				.findViewById(R.id.stundenplan_listview_flipperone);
		else
			listView = (ListView) flipper.findViewById(R.id.stundenplan_listview_flippertwo);

		List<String> unterrichtsstunden = getUnterrichtsstundenForDate(cal);

		if (unterrichtsstunden == null) {
			unterrichtsstunden = new ArrayList<String>(); 
			if (cal.getTime().getDay() == 0) 
				for (int i = 0; i < 7; i++)
					unterrichtsstunden.add("");
			else
				for (int i = 0; i < 7; i++)
					unterrichtsstunden.add("N/A");
		}

		StundenplanArrayAdapter listViewAdapter = new StundenplanArrayAdapter(activity,
				unterrichtsstunden);

		listView.setOnTouchListener(touchListener);
		listView.setAdapter(listViewAdapter);
	}

	private ArrayList<String> getUnterrichtsstundenForDate(Calendar cal) {

		for (int i = 0; i < unterrichtstage.size(); i++) {
			Unterrichtstag tag = unterrichtstage.get(i);

			if (tag.getDatum().getDate() == cal.getTime().getDate()
					&& tag.getDatum().getMonth() == cal.getTime().getMonth()
					&& tag.getDatum().getYear() == cal.getTime().getYear()) {
				return tag.getStunden();
			}
		}
		return null;
	}

	private void getActiveFlipper(LinearLayout flipper) {

		try {
			flipper.findViewById(R.id.stundenplan_flipperone).getId();
			updateFlipperOne = true;
			Log.d("badresden app", "flipperone is active");
		}
		catch (Exception e) {
			updateFlipperOne = false;
			Log.d("badresden app", "flippertwo is active");
		}
	}
}
